package com.example.parser;

import com.bob.auth.dto.request.EmployeeInsertRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * DAT文件解析器
 * 
 * @author System
 * @version 1.0.0
 */
@Slf4j
@Component
public class DatFileParser {
    
    /**
     * 字段分隔符
     */
    private static final String DELIMITER = "\\$0M\\$";
    
    /**
     * 从输入流解析Employee列表（用于远程流式读取）
     * 
     * @param inputStream 文件输入流
     * @param fileName 文件名（用于日志）
     * @return Employee请求列表
     */
    public List<EmployeeInsertRequest> parseEmployeeStream(InputStream inputStream, String fileName) throws IOException {
        List<EmployeeInsertRequest> employees = new ArrayList<>();
        
        log.info("开始解析文件流：{}", fileName);
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            
            String line;
            int lineNumber = 0;
            int successCount = 0;
            int failCount = 0;
            
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                // 解析单行
                EmployeeInsertRequest employee = parseLine(line, lineNumber);
                
                if (employee != null) {
                    employees.add(employee);
                    successCount++;
                } else {
                    failCount++;
                }
            }
            
            log.info("文件流解析完成：{}，总行数：{}，成功：{}，失败：{}", 
                fileName, lineNumber, successCount, failCount);
        }
        
        return employees;
    }
    
    /**
     * 解析DAT文件为Employee列表
     * 
     * @param file DAT文件
     * @return Employee请求列表
     */
    public List<EmployeeInsertRequest> parseEmployeeFile(File file) throws IOException {
        List<EmployeeInsertRequest> employees = new ArrayList<>();
        
        log.info("开始解析文件：{}", file.getAbsolutePath());
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            
            String line;
            int lineNumber = 0;
            int successCount = 0;
            int failCount = 0;
            
            while ((line = reader.readLine()) != null) {
                lineNumber++;
                
                // 跳过空行
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                try {
                    EmployeeInsertRequest employee = parseLine(line, lineNumber);
                    if (employee != null) {
                        employees.add(employee);
                        successCount++;
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    failCount++;
                    log.error("解析第{}行失败：{}，内容：{}", lineNumber, e.getMessage(), line);
                }
            }
            
            log.info("文件解析完成，总行数：{}，成功：{}，失败：{}", lineNumber, successCount, failCount);
        }
        
        return employees;
    }
    
    /**
     * 解析单行数据
     * 
     * 数据格式：id$0M$userCode$0M$姓名$0M$某字段$0M$orgCode$0M$orgName
     * 示例：649804$0M$016884$0M$叶$0M$ba4d046e4cdc43b9854a6d6a088520$0M$5003207$0M$总行__财富平台
     * 
     * @param line 行内容
     * @param lineNumber 行号
     * @return EmployeeInsertRequest对象
     */
    private EmployeeInsertRequest parseLine(String line, int lineNumber) {
        // 按分隔符切分
        String[] fields = line.split(DELIMITER);
        
        if (fields.length < 6) {
            log.warn("第{}行字段数量不足（需要至少6个字段，实际{}个），跳过该行", lineNumber, fields.length);
            return null;
        }
        
        try {
            EmployeeInsertRequest employee = new EmployeeInsertRequest();
            
            // 字段0: ID
            String id = fields[0].trim();
            if (id.isEmpty()) {
                log.warn("第{}行ID为空，使用UUID生成", lineNumber);
                id = UUID.randomUUID().toString();
            }
            employee.setId(id);
            
            // 字段1: UserCode
            String userCode = fields[1].trim();
            if (userCode.isEmpty()) {
                log.warn("第{}行UserCode为空，使用ID代替", lineNumber);
                userCode = id;
            }
            employee.setUserCode(userCode);
            
            // 字段2: 姓名（跳过，因为Employee表没有name字段）
            // String name = fields[2].trim();
            
            // 字段3: 某个字段（可能是cOrgId）
            String orgId = fields[3].trim();
            if (orgId.isEmpty()) {
                // 如果为空，使用UUID生成
                orgId = UUID.randomUUID().toString();
            }
            employee.setCOrgId(orgId);
            
            // 字段4: 组织编码
            String orgCode = fields[4].trim();
            if (orgCode.isEmpty()) {
                orgCode = "DEFAULT";
            }
            employee.setCOrgCode(orgCode);
            
            // 字段5: 组织名称
            String orgName = fields[5].trim();
            if (orgName.isEmpty()) {
                orgName = "未知组织";
            }
            employee.setCOrgName(orgName);
            
            return employee;
            
        } catch (Exception e) {
            log.error("第{}行数据解析异常：{}", lineNumber, e.getMessage());
            return null;
        }
    }
    
    /**
     * 解析文件并限制行数（用于测试）
     * 
     * @param file DAT文件
     * @param maxLines 最大行数
     * @return Employee请求列表
     */
    public List<EmployeeInsertRequest> parseEmployeeFile(File file, int maxLines) throws IOException {
        List<EmployeeInsertRequest> employees = new ArrayList<>();
        
        log.info("开始解析文件（限制前{}行）：{}", maxLines, file.getAbsolutePath());
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            
            String line;
            int lineNumber = 0;
            int successCount = 0;
            
            while ((line = reader.readLine()) != null && successCount < maxLines) {
                lineNumber++;
                
                if (line.trim().isEmpty()) {
                    continue;
                }
                
                try {
                    EmployeeInsertRequest employee = parseLine(line, lineNumber);
                    if (employee != null) {
                        employees.add(employee);
                        successCount++;
                    }
                } catch (Exception e) {
                    log.error("解析第{}行失败：{}", lineNumber, e.getMessage());
                }
            }
            
            log.info("文件解析完成，成功解析：{} 条", successCount);
        }
        
        return employees;
    }
}
